package com.fa4j.product.item.controller;


import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.Page;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.common.web.annotation.ApiMethod;
import com.fa4j.common.web.model.AppType;
import com.fa4j.product.item.model.*;
import com.fa4j.product.item.repository.ItemRepository;
import com.fa4j.product.item.service.ItemService;
import com.fa4j.system.file.service.FileUrlFillService;
import com.fa4j.system.login.util.LoginUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Web接口-商品信息
 *
 * @since 2025-11-22 21:06:24
 */
@RestController
@RequestMapping("product/item")
@RequiredArgsConstructor
public class ItemController {

    private final ItemService itemService;
    private final FileUrlFillService fileUrlFillService;
    private final ItemRepository itemRepository;

    @PostMapping
    @ApiMethod(name = "商品信息-创建", type = AppType.MANAGE)
    public Item create(@Valid @RequestBody ItemCreateCmd cmd) {
        Item item = itemService.create(cmd);
        fillFileUrl(List.of(item));
        return item;
    }

    @PatchMapping
    @ApiMethod(name = "商品信息-编辑", type = AppType.MANAGE)
    public Item modify(@Valid @RequestBody ItemModifyCmd cmd) {
        Item item = itemService.modify(cmd);
        fillFileUrl(List.of(item));
        return item;
    }

    @PatchMapping("state")
    @ApiMethod(name = "商品信息-修改状态", type = AppType.MANAGE)
    public void changeState(@Valid @RequestBody ItemStateChangeCmd cmd) {
        itemService.changeState(cmd);
    }

    @DeleteMapping("{id}")
    @ApiMethod(name = "商品信息-删除", type = AppType.MANAGE)
    public Item remove(@PathVariable Integer id) {
        Item item = itemService.remove(RemoveCmd.of(id, LoginUtil.getAccountId()));
        fillFileUrl(List.of(item));
        return item;
    }

    @GetMapping("{id}")
    @ApiMethod(name = "商品信息-详情查询", type = AppType.MANAGE)
    public Item detail(@PathVariable Integer id) {
        return itemRepository.findById(id)
                .map(item -> {
                    fillFileUrl(List.of(item));
                    return item;
                })
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("商品信息"));
    }

    @GetMapping("page")
    @ApiMethod(name = "商品信息-分页查询", type = AppType.MANAGE)
    public Page<Item> page(ItemPageQuery query) {
        Page<Item> page = itemRepository.queryPage(query);
        fillFileUrl(page.getRecords());
        return page;
    }

    private void fillFileUrl(List<Item> list) {
        List<Long> mediaIds = list.stream().flatMap(item -> {
            Set<Long> ids = new HashSet<>();
            if (!ObjectUtils.isEmpty(item.getMediaIds())) {
                ids.addAll(item.getMediaIds());
            }
            if (!ObjectUtils.isEmpty(item.getDetailImgIds())) {
                ids.addAll(item.getDetailImgIds());
            }
            if (!ObjectUtils.isEmpty(item.getSpecList())) {
                for (ItemSpec spec : item.getSpecList()) {
                    ids.add(spec.getImageId());
                }
            }
            return ids.stream().filter(Objects::nonNull);
        }).toList();
        Map<Long, String> fileUrlMap = fileUrlFillService.queryFileUrl(mediaIds);
        for (Item item : list) {
            if (item.getMediaIds() != null) {
                item.setMediaUrls(item.getMediaIds().stream().map(fileUrlMap::get).filter(Objects::nonNull).toList());
            }
            if (item.getDetailImgIds() != null) {
                item.setDetailImgUrls(item.getDetailImgIds().stream().map(fileUrlMap::get).filter(Objects::nonNull).toList());
            }
            if (item.getSpecList() != null) {
                for (ItemSpec spec : item.getSpecList()) {
                    spec.setImageUrl(fileUrlMap.get(spec.getImageId()));
                }
            }
        }
    }
}

